<template>
  <div class="page-project-manage">
    <div class="head-button">
      <el-button icon="iconfont iconxinzeng" circle @click="add"></el-button>
      <el-button icon="iconfont icondayin" circle @click="dayin"></el-button>
<!--      <el-button icon="iconfont icondaochu" circle @click="daochu"></el-button>-->
      <el-button icon="iconfont iconshuaxin" circle @click="reload"></el-button>
    </div>
    <div class="card-table" id="sy-card-table">
      <grid-line :headList="columns"
                 @mouseover="mouseover" :sourceData="sourceData" @lineClick="linkName">
        <template v-slot:icon="{item, index}">
          <div class="column-img">
            <img :src="images[Number(hoverLine === index)]">
          </div>
        </template>
        <template v-slot:Name="{item, index}">
          <a class="link-name" :class="{hover: hoverLine === index}" @click.prevent="linkName(item)"
             :href="`/view/project/details/${item.Id}`" target="_self">{{ item.Name }}</a>
        </template>
        <template v-slot:Aliasname="{item, index}">
          <a class="link-name" @click.prevent="linkName(item)" :href="`/view/project/details/${item.Id}`" target="_self">{{ item.Aliasname }}</a>
        </template>
        <template v-slot:operate="{item, index}">
          <el-dropdown class="operate" @command="handleOperateCommand($event, item)" v-if="btnPermissionUtil.getBtnbtnPermission('project-edit')">
            <el-button type="info">
              <span class="txt">
                操作<i class="iconfont iconzhankai2"></i>
              </span>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="-1">编辑</el-dropdown-item>
              <el-dropdown-item :command="0" divided>挂起</el-dropdown-item>
              <el-dropdown-item :command="1">延期</el-dropdown-item>
              <el-dropdown-item :command="2" divided>进行</el-dropdown-item>
              <el-dropdown-item :command="3">结束</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </grid-line>
      <vxe-pager
          :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
          :current-page.sync="queryParams.p"
          :page-size.sync="queryParams.pageoffset"
          :total="queryParams.totalCount"
          @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <add :visible.sync="addVisible" @create="reload"></add>
    <edit :visible.sync="editVisible" :editItem="editItem" @update="reload"></edit>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import DictionarySelect from '@/components/element/DictionarySelect';
import Edit from './Edit';
import Add from './Add';
import projectApi from '@/api/projectApi';
import * as filters from '@/filters/index';
import { mapGetters } from 'vuex';
import GridLine from "@/components/element/grid/line";

export default {
  components: {
    DictionarySelect,
    Add,
    Edit,
    GridLine
  },
  computed: {
    ...mapGetters(['dictionary']),
    statusList () {
      return this.dictionary.filter(item => item.DictTypeCode === 'PROJECT_STATUS')
    },
    statusFilterOptions () {
      return this.statusList.map(s => ({ label: s.DictName, value: parseInt(s.DictId) }))
    }
  },
  data () {
    return {
      images: [require('@/assets/img/project1.png'), require('@/assets/img/project2.png')],
      hoverLine: -1,
      defaultSrc: require('@/assets/img/img.jpg'),
      loading: false,
      addVisible: false,
      editVisible: false,
      editItem: {},
      queryParams: {
        status: '',
        name: '',
        p: 1,
        pageoffset: 100,
        totalCount: 0
      },
      sourceData: [],

      columns: [
        {
          field: 'icon',
          title: '',
          width: '80px',
          align: 'center',
          resizable: false,
          slot: 'icon'
        },
        {
          field: 'Name',
          title: '名称',
          sortable: true,
          align: 'center',
          resizable: false,
          slot: 'Name'
        },
        {
          field: 'Aliasname',
          title: '别名',
          align: 'center',
          resizable: false,
          slot: 'Aliasname'
        },
        {
          field: 'Produserrealname',
          title: '创建人',
          width: '160px',
          align: 'center',
          resizable: false
        },
        {
          field: 'Projuserrealname',
          title: '负责人',
          width: '160px',
          align: 'center',
          resizable: false
        },
        {
          field: 'Ended',
          title: '结束时间',
          align: 'center',
          resizable: false,
          formatter: (row) => {
            let a = ''
            if (row.Ended && (row.Ended.toString()).length > 0 && row.Ended > 0) {
              a = filters.formatDatetime(row.Ended)
            }
            return a
          }
        },
        {
          field: 'Status',
          title: '状态',
          align: 'center',
          resizable: false,
          formatter: (row) => {
            return this.formatStatus({cellValue: row.Status})
          }
        },
        {
          title: '操作',
          align: 'center',
          resizable: false,
          slot: 'operate'
        }
      ],
      gridOptions: {
        border: true,
        resizable: true,
        showHeaderOverflow: true,
        showOverflow: true,
        highlightHoverRow: true,
        keepSource: true,
        id: 'full_edit_grid',
        height: 600,
        rowId: 'id',
        customConfig: {
          storage: true,
          checkMethod: this.checkColumnMethod
        },
        sortConfig: {
          trigger: 'cell'
        },
        filterConfig: {
          remote: true
        },
        pagerConfig: {
          pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000]
        },
        toolbar: {
          slots: {
            buttons: 'toolbar-buttons'
          },
          refresh: true,
          export: true,
          print: true,
          zoom: true,
          custom: true
        },
        proxyConfig: {
          seq: true, // 启用动态序号代理
          sort: false, // 启用排序代理
          filter: true, // 启用筛选代理
          form: true, // 启用表单代理
          props: {
            result: 'Projects',
            total: 'Total'
          },
          ajax: {
            query: ({ page, sort, filters, form }) => {
              // 处理查询参数
              const queryParams = Object.assign({
                p: page.currentPage,
                pageoffset: page.pageSize
              }, form);
              const statusFilter = filters.filter(f => f.property === 'Status')[0];
              if (statusFilter) queryParams.status = statusFilter.values[0];
              const nameFilter = filters.filter(f => f.property === 'Name')[0];
              if (nameFilter) queryParams.keywords = nameFilter.datas[0];
              return new Promise(resolve => {
                projectApi.getPage(queryParams).then(res => {
                  res.Projects.forEach(i => {
                    i.Created *= 1000;
                    i.Started *= 1000;
                    i.Ended *= 1000;
                  });
                  resolve(res);
                }).catch(() => resolve([]));
              });
            }
          }
        },
        columns: [
          {
            field: 'icon',
            title: '',
            width: '80',
            align: 'center',
            resizable: false,
            slots: {
              default: ({row, column}) => [ <img src={this.defaultSrc} style="height: 30px; width: 30px"></img> ],
              filter: 'name-filter'
            }
          },
          {
            field: 'Name',
            title: '名称',
            sortable: true,
            align: 'center',
            filters: [{ data: '' }],
            resizable: false,
            slots: {
              default: ({row, column}) => [ <a class="link-name" onclick={(e) => {this.linkName(row, e);return false}} href={`/view/project/details/${row.Id}`} target="_self">{row.Name}</a> ],
              filter: 'name-filter'
            }
          },
          {
            field: 'Aliasname',
            title: '别名',
            align: 'center',
            resizable: false,
            slots: {
              default: ({row, column}) => [ <a class="link-name" onclick={(e) => {this.linkName(row, e);return false}} href={`/view/project/details/${row.Id}`} target="_self">{row.Aliasname}</a> ]
            }
          },
          {
            field: 'Produserrealname',
            title: '创建人',
            width: '160',
            align: 'center',
            resizable: false
          },
          {
            field: 'Projuserrealname',
            title: '负责人',
            width: '160',
            align: 'center',
            resizable: false
          },
          {
            field: 'Ended',
            title: '结束时间',
            align: 'center',
            resizable: false,
            slots: {
              default: ({row, column}) => {
                let a = ''
                if (row.Ended && (row.Ended.toString()).length > 0 && row.Ended > 0) {
                  a = filters.formatDatetime(row.Ended)
                }
                return [ <span>{a}</span> ]
              }
            }
          },
          {
            field: 'Status',
            title: '状态',
            width: '124',
            align: 'center',
            resizable: false,
            formatter: this.formatStatus,
            filters: this.getStatusFilterOptions(),
            filterMultiple: false,
            editRender: {
              name: '$select',
              options: this.getStatusFilterOptions()
            }
          },
          {
            title: '操作',
            align: 'center',
            resizable: false,
            slots: {
              default: 'operate'
            }
          }
        ],
        exportConfig: {
          remote: true,
          types: ['csv'],
          modes: ['current', 'selected', 'all']
        },
        checkboxConfig: {
          labelField: 'id',
          reserve: true,
          highlight: true,
          range: true
        }
      }
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    handlePageChange ({ currentPage, pageSize }) {
      console.log(currentPage, pageSize)
      this.queryParams.p = currentPage
      this.queryParams.pageoffset = pageSize
      this.loadData()
    },
    daochu () {
      this.$message.warning('暂未实现');
    },
    dayin () {
      this.Print('sy-card-table')
    },
    Print(obj) {
      var str = document.getElementById(obj).innerHTML     //获取需要打印的页面元素
      str ="<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head><body>"+str+"</body></html>";
      let pwin=window.open("Print.htm","print");
      //PageSetup_Default();//设置页眉和页脚为默认值
      pwin.document.write(str);
      pwin.document.close();                   //这句很重要，没有就无法实现
      pwin.print();
    },
    add () {
      this.addVisible = true
    },
    // 获取数据
    mouseover (item, index) {
      this.hoverLine = index
    },
    loadData () {
      let that = this
      that.$nextTick(() => {
        projectApi.getPage(that.queryParams).then(res => {
          res.Projects.forEach(i => {
            i.Created *= 1000;
            i.Started *= 1000;
            i.Ended *= 1000;
          });
          that.sourceData = res.Projects
          that.queryParams.totalCount = res.Total
        }).catch(() => that.sourceData = []);
      })
    },
    // 点击A标签
    linkName (row, e) {
      this.$router.push({
        path: `/view/project/details/${row.Id}`
      })
      // e.preventDefault()
      // return false
    },
    getStatusFilterOptions () {
      return this.$store.state.sys.dictionary
        .filter(item => item.DictTypeCode === 'PROJECT_STATUS')
        .map(item => ({ label: item.DictName, value: parseInt(item.DictId) }));
    },
    formatStatus ({ cellValue }) {
      const res = this.statusFilterOptions.find(item => item.value === cellValue);
      return res ? res.label : cellValue;
    },
    checkColumnMethod ({ column }) {
      return !['name', 'alias'].includes(column.property);
    },
    exportMethod () {
      this.$message.warning('此方法需要后端接口支持');
      return Promise.resolve(true);
    },
    save () {
      // const promises = this.$refs.xGrid.getUpdateRecords().map(r => projectApi.modify(r));
      // if (promises.length < 1) return;
      // Promise.all(promises)
      //   .then(res => {
      //     if (res && res.code === 1) {
            this.reload();
        //     this.$message.success('保存成功');
        //   } else {
        //     this.$message.error(res.message);
        //   }
        // })
        // .catch(e => this.$message.error('保存失败'));
    },
    handleOperateCommand (command, row) {
      if (command === -1) {
        this.editItem = row;
        this.editVisible = true;
      } else {
        // if (this.$refs.xGrid.getUpdateRecords().length > 0) {
        //   this.$message.warning('请先保存已修改的数据');
        //   return
        // }
        projectApi.modifyStatus(row.Id, command)
          .then(res => {
            if (res && res.code === 1) {
              this.reload();
              this.$message.success('状态更新成功')
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(e => this.$message.error('状态更新失败'));
      }
    },
    reload () {
      // this.$refs.xGrid.commitProxy('reload');
      this.loadData()
    }
  }
}
</script>

<style lang="scss" scoped src="@/assets/css/page/projectManage/index.scss">
</style>
